class PostsController < ApplicationController
 before_filter :login_required,:only => [:new,:create,:update,:edit]
 
  
  def index
  	@tag = Tag.find(params[:id]) if params[:id]
    @title = @tag.name if @tag
    if @tag
  	@posts = Post.paginate_by_sql("select p.* from posts p join posts_tags t on p.id = t.post_id where t.tag_id='#{@tag.id}' order by updated_at desc",:page => params[:page],:per_page => 15)
    else
    @posts = Post.paginate_by_sql("select * from posts order by created_at desc",:per_page => 15,:page => params[:page])
    end

    respond_to do |format|
      format.html 
      format.xml  { render :xml => @posts }
format.rss  { render :layout => false }
    end
  end

  def show
    @main = Post.find_by_id(params[:id])
    @title = @main.title
		@posts = Post.paginate(:page => params[:page],:per_page => 15,:conditions => ["parent_id=?",@main.id])
    respond_to do |format|
      if @main.nil?
        format.html { redirect_to "/" }
      else
        format.html 
        format.xml  { render :xml => @post }
      end
    end
  end
  
  def new
  	@tags = Tag.find(:all)
  end
   
  def edit
    @post = Post.find(params[:id])
  	@tags = Tag.find(:all)
  end
  
  def create
    @post 						 = Post.new(params[:post])
    @post.title   		 = params[:title]
		@post.html_content = params[:message]

    if @post.save
    	add_post_tags(@post,params[:tags])
      flash[:notice] = '创建成功.'
      redirect_to :action => "show",:id => @post.id
    else
      format.html { render :action => "new" }
    end
  end
 
  def update

  end


  private
  
  def add_post_tags(post,tag_ids)
  	tag_ids.each do |id|
  		post.posts_tags << PostsTag.create(:post_id => post.id,:tag_id => id)
		end
	end

end
